﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using Infragistics.Win;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Excel;
namespace BYManageInfoSystem
{
    public partial class Frm_ValueAddedTaxInvoice : Form
    {
        private DGBY.BLL.FactoryDataTab m_bllFactoryDataTab = new DGBY.BLL.FactoryDataTab();
        private DGBY.BLL.ValueAddedTaxInvoiceTab m_bllValueAddedTaxInvoiceTab = new DGBY.BLL.ValueAddedTaxInvoiceTab();
        private int m_nSelectValueAddedTaxInvoiceTabID = 0;

        public class CustomMergedCellEvaluator : Infragistics.Win.UltraWinGrid.IMergedCellEvaluator
        {

            // 合并日期相同的单元格（无需时间精确相同）
            public bool ShouldCellsBeMerged(UltraGridRow row1, UltraGridRow row2, UltraGridColumn column)
            {
                string str1 = (string)row1.GetCellValue(column);
                string str2 = (string)row2.GetCellValue(column);

                return str1 == str2;

            }

        }

        private bool IsDecimal(string strInput)
        {
            bool bRet = Regex.IsMatch(strInput, @"([1-9]+[0-9]*(\.[0-9]+))|(0(\.[0-9]+))");
            return bRet;
        }

        private bool IsNum(string strInput)
        {
            bool bRet = Regex.IsMatch(strInput, @"^[1-9]+\d*$");
            return bRet;
        }

        private bool ValidDate(string strInput)
        {
            if (strInput.Length != 8)
                return false;
            else
                return IsNum(strInput);
        }

        public bool IsDecimal(ErrorProvider errorProvider1, TextBox TextBox)
        {
            if (TextBox.Text == "")
            {
                errorProvider1.SetError(TextBox, "内容不能为空！");
                return true;
            }
            else if (!IsDecimal(TextBox.Text) && !IsNum(TextBox.Text))
            {
                errorProvider1.SetError(TextBox, "必须输入数字");
                return true;
            }
            else
            {
                errorProvider1.SetError(TextBox, "");
                return false;
            }
        }

        public bool IsNum(ErrorProvider errorProvider1, TextBox TextBox)
        {
            if (TextBox.Text == "")
            {
                errorProvider1.SetError(TextBox, "内容不能为空！");
                return true;
            }
            else if (!IsNum(TextBox.Text))
            {
                errorProvider1.SetError(TextBox, "必须输入数字");
                return true;
            }
            else
            {
                errorProvider1.SetError(TextBox, "");
                return false;
            }
        }

        public bool IsNull(ErrorProvider errorProvider1, TextBox TextBox)
        {
            if (TextBox.Text == "")
            {
                errorProvider1.SetError(TextBox, "内容不能为空！");
                return true;
            }
            else
            {
                errorProvider1.SetError(TextBox, "");
                return false;
            }
        }
        public Frm_ValueAddedTaxInvoice()
        {
            InitializeComponent();
        }
        public void InitUltraWinGridSetting()
        {
            this.ultraGrid1.DisplayLayout.Override.RowSelectors = Infragistics.Win.DefaultableBoolean.True;
            this.ultraGrid1.DisplayLayout.Override.RowSelectorNumberStyle = Infragistics.Win.UltraWinGrid.RowSelectorNumberStyle.VisibleIndex;
            this.ultraGrid1.DisplayLayout.Override.RowSelectorWidth = 40;
        }

        public void LocalPrintPreveiw()
        {
            Infragistics.Shared.ResourceCustomizer rc = Infragistics.Win.Printing.Resources.Customizer;//Resources.Customizer;
            rc.SetCustomizedString("PrintPreview_DialogCaption", "打印预览");
            rc.SetCustomizedString("PrintPreview_Tool_Print", "打印(&P)");
            rc.SetCustomizedString("PrintPreview_Tool_ClosePreview", "关闭(&C)");
            rc.SetCustomizedString("PrintPreview_Tool_ContextMenuPreviewZoom", "显示比例");
            rc.SetCustomizedString("PrintPreview_Tool_Current_Page", "当前页");
            rc.SetCustomizedString("PrintPreview_Tool_Exit", "退出(&X)");
            rc.SetCustomizedString("PrintPreview_Tool_First_Page", "第一页");
            rc.SetCustomizedString("PrintPreview_Tool_Go_To", "跳至");
            rc.SetCustomizedString("PrintPreview_Tool_Last_Page", "最后一页");
            rc.SetCustomizedString("PrintPreview_Tool_Next_Page", "下一页");
            rc.SetCustomizedString("PrintPreview_Tool_Previous_Page", "前一页");
            rc.SetCustomizedString("PrintPreview_Tool_Next_View", "下一视图(&N)");
            rc.SetCustomizedString("PrintPreview_Tool_Previous_View", "前一视图(&P)");
            rc.SetCustomizedString("PrintPreview_Tool_Hand_Tool", "手型工具(&H)");
            rc.SetCustomizedString("PrintPreview_Tool_Page_Setup", "页面设置(&U)");
            rc.SetCustomizedString("PrintPreview_Tool_Snapshot_Tool", "快照工具(&S)");
            rc.SetCustomizedString("PrintPreview_Tool_View", "视图(&V)");
            rc.SetCustomizedString("PrintPreview_Tool_Whole_Page", "合适页");
            rc.SetCustomizedString("PrintPreview_Tool_Zoom", "缩放(&Z)");
            rc.SetCustomizedString("PrintPreview_Tool_Zoom_In", "放大");

            rc.SetCustomizedString("PrintPreview_Tool_Zoom_Out", "缩小");

            rc.SetCustomizedString("PrintPreview_ToolCategory_Context_Menus", "上下文菜单");
            rc.SetCustomizedString("PrintPreview_ToolCategory_File", "文件");
            rc.SetCustomizedString("PrintPreview_ToolCategory_Menus", "菜单");
            rc.SetCustomizedString("PrintPreview_ToolCategory_Tools", "工具栏");
            rc.SetCustomizedString("PrintPreview_ToolCategory_View", "视图");
            rc.SetCustomizedString("PrintPreview_ToolCategory_Zoom_Mode", "缩放模式");

            rc.SetCustomizedString("PrintPreview_ToolTip_ClosePreview", "关闭");
            rc.SetCustomizedString("PrintPreview_ToolTip_Zoom", "缩放");
            rc.SetCustomizedString("StatusBar_Page_X_OF_X", "页:{0}/{1}");

            rc.SetCustomizedString("CustomizeImg_ToolBar_MenuBar", "菜单");
            rc.SetCustomizedString("CustomizeImg_ToolBar_Standard", "标准");
            rc.SetCustomizedString("CustomizeImg_ToolBar_View", "视图");
            rc.SetCustomizedString("PrintPreview_Tool_File", "文件(&F)");
            rc.SetCustomizedString("PrintPreview_Tool_Tools", "工具(&T)");
            rc.SetCustomizedString("PrintPreview_Tool_Dynamic_Zoom_Tool", "动态缩放工具(&D)");
            rc.SetCustomizedString("PrintPreview_Tool_Zoom_Out_Tool", "缩小工具");
            rc.SetCustomizedString("PrintPreview_Tool_Zoom_In_Tool", "放大工具");
            // rc.SetCustomizedString("PrintPreview_Tool_Page_Layout","菜单");
            rc.SetCustomizedString("PreviewRowColSelection_Cancel", "取消");
            rc.SetCustomizedString("PreviewRowColSelection_SelectedPages", "{0} x {1} 页");

            rc.SetCustomizedString("PreviewRowColSelection_Cancel", "取消");
            rc.SetCustomizedString("PrintPreview_Tool_Page_Width", "页宽");
            rc.SetCustomizedString("PrintPreview_ZoomListItem_MarginWidth", "文字宽度");
            rc.SetCustomizedString("PrintPreview_ZoomListItem_PageWidth", "页宽");
            rc.SetCustomizedString("PrintPreview_ZoomListItem_WholePage", "合适页");
            rc.SetCustomizedString("PrintPreview_Tool_Page_Layout", "页面布局");
            rc.SetCustomizedString("PrintPreview_Tool_Margin_Width", "文字宽度");
            rc.SetCustomizedString("ContextMenuPreviewHand", "缩放视图");


            rc.SetCustomizedString("PrintPreview_Tool_Reduce_Page_Thumbnails", "缩小");
            rc.SetCustomizedString("PrintPreview_Tool_Show_Page_Numbers", "显示页号");
            rc.SetCustomizedString("PrintPreview_Tool_ContextMenuThumbnail", "缩略图");
            rc.SetCustomizedString("PrintPreview_Tool_Enlarge_Page_Thumbnails", "放大");
            rc.SetCustomizedString("PrintPreview_Tool_Thumbnails", "缩略图");
            rc.SetCustomizedString("PrintPreview_Tool_Continuous", "连续排序");
            //说明
            rc.SetCustomizedString("StatusBar_DynamicZoom_Instructions", "单击并拖动进行缩放操作");
            rc.SetCustomizedString("StatusBar_Page_X_OF_X", "当前页: {0} / {1}");
            rc.SetCustomizedString("StatusBar_SnapShot_Instructions", "单击并拖动,系统将选定矩型区域复制到剪帖板");
            rc.SetCustomizedString("StatusBar_ZoomIn_Instructions", "单击并拖动,系统将放大选定矩型区域");
            rc.SetCustomizedString("StatusBar_ZoomOut_Instructions", "单击并拖动,系统将缩小选定矩型区域");
            rc.SetCustomizedString("StatusBar_Hand_Instructions", "单击并拖动以便显示更多内容");
        }

        private void InitCombox()
        {
            DataSet ds = m_bllFactoryDataTab.GetList("");
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                this.comboBoxFac.DataSource = ds.Tables[0];

                this.comboBoxFac.ValueMember = "FactoryDataTabID";
                this.comboBoxFac.DisplayMember = "工厂名称";
                this.comboBoxFac.SelectedIndex = 0;
            }
        }
        private void Frm_ValueAddedTaxInvoice_Load(object sender, EventArgs e)
        {
            InitCombox();
            LocalPrintPreveiw();
            InitUltraWinGridSetting();
        }

        private void ShowAllRecord(string strWhere)
        {
            DataSet ds = m_bllValueAddedTaxInvoiceTab.GetValueAddedTaxInvoiceList(strWhere);
            
            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                DataTable dtNew = null;
                dtNew = ds.Tables[0].Clone();
                int nAcculateNum = 0;

                Decimal dTotalBGJinE = 0;
                Decimal dTotalInvoiceJinE = 0;
                Decimal dTotalShouldBackTaxJinE = 0;

                int nRowsCount = ds.Tables[0].Rows.Count;
                for (int i = 0; i < nRowsCount; i++)
                {
                    dtNew.Rows.Add(ds.Tables[0].Rows[i].ItemArray);

                    string strName = ds.Tables[0].Rows[i]["报关金额"].ToString();
                    dTotalBGJinE = Convert.ToDecimal(strName) + dTotalBGJinE;
                    strName = ds.Tables[0].Rows[i]["发票金额"].ToString();
                    dTotalInvoiceJinE = Convert.ToDecimal(strName) + dTotalInvoiceJinE;
                    strName = ds.Tables[0].Rows[i]["应退税金额"].ToString();
                    dTotalShouldBackTaxJinE = Convert.ToDecimal(strName) + dTotalShouldBackTaxJinE;


                    if (i < (nRowsCount - 1) && ds.Tables[0].Rows[i]["合同编号"].ToString() == ds.Tables[0].Rows[i + 1]["合同编号"].ToString())
                    {
                        nAcculateNum++;

                    }
                    else if (i == nRowsCount - 1)//最后一行
                    {
                        DataRow dr1 = null;
                        if (nAcculateNum > 0)
                        {
                            dr1 = dtNew.NewRow();

                            dr1["报关金额"] = dTotalBGJinE;
                            dr1["发票金额"] = dTotalInvoiceJinE;
                            dr1["应退税金额"] = dTotalShouldBackTaxJinE;


                            dr1["合同编号"] = "小计";

                            dtNew.Rows.Add(dr1.ItemArray);

                            dTotalBGJinE = 0;
                            dTotalInvoiceJinE = 0;
                            dTotalShouldBackTaxJinE = 0;
                        }

                    }
                    else
                    {
                        if (nAcculateNum > 0)
                        {
                            DataRow dr1 = dtNew.NewRow();
                            dr1 = dtNew.NewRow();

                            dr1["报关金额"] = dTotalBGJinE;
                            dr1["发票金额"] = dTotalInvoiceJinE;
                            dr1["应退税金额"] = dTotalShouldBackTaxJinE;


                            dr1["合同编号"] = "小计";

                            dtNew.Rows.Add(dr1.ItemArray);

                            dTotalBGJinE = 0;
                            dTotalInvoiceJinE = 0;
                            dTotalShouldBackTaxJinE = 0;
                        }
                        nAcculateNum = 0;
                    }
                }

                ultraGrid1.DataSource = dtNew;

                ultraGrid1.DisplayLayout.Bands[0].Columns[0].Hidden = true;
                ultraGrid1.DisplayLayout.Bands[0].Columns[1].Hidden = true;
            }
        }

        private void buttonShowAll_Click(object sender, EventArgs e)
        {
            ShowAllRecord("");
        }

        /// 取得某月的第一天
        /// </summary>
        /// <param name="datetime">要取得月份第一天的时间</param>
        /// <returns></returns>
        private DateTime FirstDayOfMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day);
        }
        /// <summary>
        /// 取得某月的最后一天
        /// </summary>
        /// <param name="datetime">要取得月份最后一天的时间</param>
        /// <returns></returns>
        private DateTime LastDayOfMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day).AddMonths(1).AddDays(-1);
        }

        /// <summary>
        /// 取得上个月第一天
        /// </summary>
        /// <param name="datetime">要取得上个月第一天的当前时间</param>
        /// <returns></returns>
        private DateTime FirstDayOfPreviousMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day).AddMonths(-1);
        }

        /// <summary>
        /// 取得上个月的最后一天
        /// </summary>
        /// <param name="datetime">要取得上个月最后一天的当前时间</param>
        /// <returns></returns>
        private DateTime LastDayOfPrdviousMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day).AddDays(-1);
        }


        private void buttonQuery_Click(object sender, EventArgs e)
        {
            DateTime dtFirstDay = FirstDayOfMonth(this.dateTimePickerFrom.Value);
            DateTime dtLastDay = LastDayOfMonth(this.dateTimePickerFrom.Value);
            ShowAllRecord(@"FacConPeoAndTelTab.FactoryDataTabID = '" + this.comboBoxFac.SelectedValue + "'"
                                                               + " and BGDComeBackTab.SBDate >= '" + dtFirstDay + "'" + " and BGDComeBackTab.SBDate <= '" + dtLastDay + "'");

        }

        private void ultraGrid1_AfterCellActivate(object sender, EventArgs e)
        {
            if ("小计" == this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["合同编号"].Text)
                return;
            string strValueAddedTaxInvoiceTabID = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells[0].Text;
            m_nSelectValueAddedTaxInvoiceTabID = Convert.ToInt32(strValueAddedTaxInvoiceTabID, 10);
            cellValueAddedTaxInvoiceTabClick();
        }

        private void cellValueAddedTaxInvoiceTabClick()
        {
            DGBY.Model.ValueAddedTaxInvoiceTab modelValueAddedTaxInvoiceTab = m_bllValueAddedTaxInvoiceTab.GetModel(m_nSelectValueAddedTaxInvoiceTabID);
            if (modelValueAddedTaxInvoiceTab != null)
            {

                this.textBoxContractNo.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["合同编号"].Text;
                
                this.textBoxSeagateJinE.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["报关金额"].Text;
                this.textBoxWithTaxPrice.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["含税价"].Text;
                this.textBoxInvoiceNo.Text = modelValueAddedTaxInvoiceTab.InvoiceNo.ToString();
                this.textBoxInvoiceJinE.Text = modelValueAddedTaxInvoiceTab.InvoiceJinE.ToString();
                this.textBoxShouldBackTax.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["应退税金额"].Text;
                this.textBoxBackTaxFact.Text = modelValueAddedTaxInvoiceTab.TrueBackTaxJinE.ToString();
                this.textBoxReason.Text = modelValueAddedTaxInvoiceTab.RejectBackTaxReason.ToString();
                this.textBoxChaE.Text = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["差额"].Text;


                this.comboBoxFac.SelectedValue = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells["FactoryDataTabID"].Text;


                this.dateTimePickerKaiPiaoDate.Value = (System.DateTime)modelValueAddedTaxInvoiceTab.TakeInvoiceDate;
                this.dateTimePickerBackTaxDate.Value = (System.DateTime)modelValueAddedTaxInvoiceTab.BackTaxDate;
            }
        }

        private void buttonModify_Click(object sender, EventArgs e)
        {
            try
            {
                if (ClassInputValid.IsDecimal(this.errorProvider1, this.textBoxInvoiceJinE))
                    return;
                if (ClassInputValid.IsDecimal(this.errorProvider1, this.textBoxBackTaxFact))
                    return;

                DGBY.Model.ValueAddedTaxInvoiceTab modelValueAddedTaxInvoiceTabOld = m_bllValueAddedTaxInvoiceTab.GetModel(m_nSelectValueAddedTaxInvoiceTabID);
                if (modelValueAddedTaxInvoiceTabOld == null)
                {
                    MessageBox.Show("数据库不存在该记录!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                DGBY.Model.ValueAddedTaxInvoiceTab modelValueAddedTaxInvoiceTab = new DGBY.Model.ValueAddedTaxInvoiceTab();

                modelValueAddedTaxInvoiceTab.ValueAddedTaxInvoiceTabID = m_nSelectValueAddedTaxInvoiceTabID;
                modelValueAddedTaxInvoiceTab.FacMakeInvoiceSplitTabID = modelValueAddedTaxInvoiceTabOld.FacMakeInvoiceSplitTabID;
                modelValueAddedTaxInvoiceTab.InvoiceNo = this.textBoxInvoiceNo.Text;
                modelValueAddedTaxInvoiceTab.InvoiceJinE = Convert.ToDecimal(this.textBoxInvoiceJinE.Text);
                modelValueAddedTaxInvoiceTab.TrueBackTaxJinE = Convert.ToDecimal(this.textBoxBackTaxFact.Text);
                modelValueAddedTaxInvoiceTab.RejectBackTaxReason = this.textBoxReason.Text;



                modelValueAddedTaxInvoiceTab.TakeInvoiceDate = this.dateTimePickerKaiPiaoDate.Value;
                modelValueAddedTaxInvoiceTab.BackTaxDate = this.dateTimePickerBackTaxDate.Value;


                m_bllValueAddedTaxInvoiceTab.Update(modelValueAddedTaxInvoiceTab);
                ShowAllRecord("");
                MessageBox.Show("数据修改成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
           
        }

        private void buttonExportToExcel_Click(object sender, EventArgs e)
        {
            DataTable dt = (DataTable)ultraGrid1.DataSource;

            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.Filter = "Excel文件(*.xls)|*.xls";
                    string outFile = "";

                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        outFile = sfd.FileName;
                    }
                    else
                    {
                        return;
                    }

                    ultraGridExcelExporter1.Export(ultraGrid1, outFile);
                }
            }
        }

        private void buttonPrint_Click(object sender, EventArgs e)
        {
            //foreach (UltraGridColumn ugc in ultraGrid1.DisplayLayout.Bands[0].Columns)
            //    ugc.Width++;
            this.ultraGridPrintDocument1.Grid = this.ultraGrid1;
            this.ultraPrintPreviewDialog1.Document = this.ultraGridPrintDocument1;
            this.ultraPrintPreviewDialog1.ShowDialog(this);
        }

        private void ultraGrid1_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            //ultraGrid1.DisplayLayout.Bands[0].UseRowLayout = true;
            //ultraGrid1.DisplayLayout.Override.RowSizing = RowSizing.AutoFree;
            //foreach (UltraGridColumn ugc in ultraGrid1.DisplayLayout.Bands[0].Columns)
            //    ugc.PerformAutoResize();
        }

        private void ultraGrid1_InitializeRow(object sender, InitializeRowEventArgs e)
        {
            ultraGrid1.DisplayLayout.Override.CellAppearance.TextHAlign = HAlign.Center;
            ultraGrid1.DisplayLayout.Override.CellAppearance.TextVAlign = VAlign.Middle;
            ultraGrid1.DisplayLayout.Override.MergedCellAppearance.TextHAlign = HAlign.Center;
            ultraGrid1.DisplayLayout.Override.MergedCellAppearance.TextVAlign = VAlign.Middle;

            ultraGrid1.DisplayLayout.Bands[0].Columns["合同编号"].MergedCellStyle = MergedCellStyle.Always;


            ultraGrid1.DisplayLayout.Bands[0].Columns["合同编号"].MergedCellEvaluator = new
   CustomMergedCellEvaluator();

        }


    }
}